package gov.kqqzyyy.monkey.ydhl.ui;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.support.design.widget.TextInputEditText;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.Toast;

import butterknife.BindView;
import butterknife.ButterKnife;
import gov.kqqzyyy.monkey.ydhl.R;
import mytools.CurrentVersion;
import mytools.MyBaseActivity;
import mytools.MyServiceUtil;
import mytools.NetWorkUtil;
import objects.LoginUser;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import service.UpdateService;

/**
 * A login screen that offers login via email/password.
 */
public class UserLoginActivity extends NavigationBaseActivity implements Button.OnClickListener {

    @BindView(R.id.container)
    FrameLayout container;

    AutoCompleteTextView mAccountView;
    TextInputEditText mPasswordView;
    Button mAccountSignInButton;

    private boolean isNetworkAvailable = false, isLastVersion = false;

    private UpdateReceiver updateReceiver = null;//更新广播接收器
    private Intent serviceIntent;//更新Intent
    private int newVerCode;//新版本版本号
    private String newVerName;//新版本版本名称

    private long firstTime = 0;
    private boolean isLogining = false;

    private Call<String> loginUserCall;

    private Handler myHandler = new Handler();
    private Runnable mLoadingRunnable = this::loadView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        setContentView(R.layout.activity_login);
        ButterKnife.bind(this);

        serviceIntent = new Intent(this, UpdateService.class);
        updateReceiver = new UpdateReceiver();
        IntentFilter intentFilter = new IntentFilter("updatebroadcast");
        this.registerReceiver(updateReceiver, intentFilter);
    }

    private void loadView() {
        container.removeAllViews();
        LayoutInflater.from(this).inflate(R.layout.activity_login, container);
        onBindUI();
        String account = getMySharedPreferences().getString("account", "");
        String password = getMySharedPreferences().getString("password", "");
        if (!account.equals("")) {
            mAccountView.setText(account);
        }
        if (!password.equals("")) {
            mPasswordView.setText(password);
        }
        mPasswordView.setOnEditorActionListener((textView, id, keyEvent) -> {
            if (id == R.id.login || id == EditorInfo.IME_NULL) {
                attemptLogin();
                return true;
            }
            return false;
        });
        mAccountSignInButton.setOnClickListener(this);
        setActionBarText("用户登陆");
    }

    private void onBindUI() {
        mAccountView = findViewById(R.id.account);
        mPasswordView = findViewById(R.id.password);
        mAccountSignInButton = findViewById(R.id.account_sign_in_button);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.account_sign_in_button:
                if (isNetworkAvailable) {
                    if (isLastVersion) {
                        if (!getMySharedPreferences().getString("SBXH", "").equals("")) {
                            attemptLogin();
                        } else {
                            showCenterToast("设备信息获取失败，无法登陆！");
                        }
                    } else {
                        showCenterToast("应用不是最新版本无法登陆！");
                    }
                } else {
                    showCenterToast("网络连接不可用！");
                }
                break;
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            if (isLogining) {
                if (loginUserCall != null && loginUserCall.isExecuted()) {
                    loginUserCall.cancel();
                }
            } else {
                long secondTime = System.currentTimeMillis();
                if (secondTime - firstTime > 2000) {
                    Toast.makeText(getApplicationContext(), "再按一次退出程序", Toast.LENGTH_SHORT).show();
                    firstTime = secondTime;
                    return true;
                } else {
                    System.exit(0);
                }
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onResume() {
        super.onResume();
        getWindow().getDecorView().post(() -> myHandler.post(mLoadingRunnable));
        isNetworkAvailable = false;
        isLastVersion = false;
        isLogining = false;
        startService(serviceIntent);
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (loginUserCall != null && loginUserCall.isExecuted()) {
            loginUserCall.cancel();
        }
        stopService(serviceIntent);

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(updateReceiver);
    }

    private void attemptLogin() {
        mAccountView.setError(null);
        mPasswordView.setError(null);
        String account = mAccountView.getText().toString();
        String password = mPasswordView.getText().toString();
        if (TextUtils.isEmpty(account)) {
            mAccountView.setError(getString(R.string.error_field_required));
            mAccountView.requestFocus();
        } else {
            if (TextUtils.isEmpty(password)) {
                password = "";
            }
            getLoginUser(account, password);
        }
    }

//    @Override
//    public Loader<Cursor> onCreateLoader(int i, Bundle bundle) {
//        return new CursorLoader(this,
//                // Retrieve data rows for the device user's 'profile' contact.
//                Uri.withAppendedPath(ContactsContract.Profile.CONTENT_URI,
//                        ContactsContract.Contacts.Data.CONTENT_DIRECTORY), ProfileQuery.PROJECTION,
//                ContactsContract.Contacts.Data.MIMETYPE +
//                        " = ?", new String[]{ContactsContract.CommonDataKinds.Email
//                .CONTENT_ITEM_TYPE},
//                ContactsContract.Contacts.Data.IS_PRIMARY + " DESC");
//    }

//    @Override
//    public void onLoadFinished(Loader<Cursor> cursorLoader, Cursor cursor) {
//        List<String> accounts = new ArrayList<>();
//        cursor.moveToFirst();
//        while (!cursor.isAfterLast()) {
//            accounts.add(cursor.getString(ProfileQuery.ADDRESS));
//            cursor.moveToNext();
//        }
//        addAccountsToAutoComplete(accounts);
//    }

//    @Override
//    public void onLoaderReset(Loader<Cursor> cursorLoader) {
//    }

//    private void addAccountsToAutoComplete(List<String> accountCollection) {
//        //Create adapter to tell the AutoCompleteTextView what to show in its dropdown list.
//        ArrayAdapter<String> adapter =
//                new ArrayAdapter<>(UserLoginActivity.this,
//                        android.R.layout.simple_dropdown_item_1line, accountCollection);
//
//        mAccountView.setAdapter(adapter);
//    }

//    private interface ProfileQuery {
//        String[] PROJECTION = {
//                ContactsContract.CommonDataKinds.Email.ADDRESS,
//                ContactsContract.CommonDataKinds.Email.IS_PRIMARY,
//        };
//
//        int ADDRESS = 0;
//    }

    private void doLogIn(LoginUser user) {
        Intent intent;
        if (!user.getYGGH().equals(getMySharedPreferences().getString("account", ""))) {
            getMyApplication().setChoosePatient(null);
            intent = new Intent(getApplicationContext(), SectionActivity.class);
        } else {
            intent = new Intent(getApplicationContext(), PatientDetailActivity.class);
        }
        startActivity(intent);
    }

    /***
     * 广播接收器
     */
    private class UpdateReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            int code = intent.getIntExtra("updatecode", -1);
            if (code != 0x17) {
                isNetworkAvailable = true;
                if (getMySharedPreferences().getString("SBXH", "").equals("")) {
                    doGetSBXH(getMyApplication().getDeviceInfos().get("SERIAL"), NetWorkUtil.IPV4_ADD, "");
                }
            }
            Intent broadIntent = new Intent("toUpdateService");
            switch (code) {
                case 0x11://系统版本最新
                    isLastVersion = true;
                    showCenterToast("应用已是最新版本！");
                    doUploadLogFile();
                    break;
                case 0x12://检测到新版本
                    newVerCode = intent.getIntExtra("newVerCode", -1);
                    newVerName = intent.getStringExtra("newVerName");
                    showUpdateDialog();
                    break;
                case 0x13://更新文件下载完成
                    cancelProgressDialog();
                    broadIntent.putExtra("toservice", 0x13);
                    sendBroadcast(broadIntent);//发送安装通知
                    break;
                case 0x14://下载文件不存在
                    showCenterToast("下载文件不存在！");
                    break;
                case 0x15://下载文件超时
                    showCenterToast("下载超时！");
                    break;
                case 0x17://网络未连接
                    showCenterToast("网络未连接！");
                    break;
                case 0x18://无法连接到服务器
                    showCenterToast("获取更新数据失败！");
                    break;
            }
        }
    }

    private void showCenterToast(String message) {
        cancelProgressDialog();
        Toast toast = Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT);
        toast.setGravity(Gravity.CENTER, 0, 0);
        toast.show();
    }

    /**
     * 更新提示对话框
     */
    private void showUpdateDialog() {
        cancelProgressDialog();
        String message = "";
        final Intent intent = new Intent("toUpdateService");
        message += "当前版本：" + CurrentVersion.getVerName(this) + "\n";
        message += "版本号：" + CurrentVersion.getVerCode(this) + "\n";
        message += "发现新版本：" + newVerName + "\n";
        message += "版本号：" + newVerCode + "\n";
        message += "是否更新？";
        Dialog dialog = new AlertDialog.Builder(this)
                .setTitle("软件更新")
                .setMessage(message)
                .setCancelable(false)
                .setPositiveButton("确定", (dialog1, which) -> {
                    intent.putExtra("toservice", 0x11);
                    sendBroadcast(intent);
                    dialog1.dismiss();
                    showProgressDialog("下载新版本中");
                }).setNegativeButton("取消", (dialog12, which) -> dialog12.dismiss()).create();
        dialog.show();
    }

    private void getLoginUser(String account, String password) {
        showProgressDialog("登陆中");
        isLogining = true;
        loginUserCall = MyServiceUtil.getLoginUserCall(account, password);
        Callback<String> callback = new Callback<String>() {
            @Override
            public void onResponse(Call<String> call, Response<String> response) {
                cancelProgressDialog();
                isLogining = false;
                String result = response.body();
                if (result != null) {

                }

            }

            @Override
            public void onFailure(Call<String> call, Throwable t) {
                cancelProgressDialog();
                isLogining = false;
                showCenterToast("获取登陆数据失败!");
            }
        };
        loginUserCall.enqueue(callback);

    }


}

